// pages/movies/movies.js
let util = require("../../util/util.js")
let app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    base_url: app.globalData.tmdb_config.base_url,
    poster_sizes: app.globalData.tmdb_config.poster_sizes,
    searchResults: {}, //搜索结果
    insearch: false //进入搜索模式
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    /**
     * 正在热映，即将上映，top
     */
    this.setData({
      moviesList: new Array()
    });
    for (var i = 0; i <= 2; i++) {
      util.Movies_RequestMovieList(util.Movies_GetListUrlFromListId(i, 0), i, 3, this.Movies_SetPage)
    }
    //也可以这样写
    // this.setData({
    //   'moviesList[0].listTitle': '正在热映'
    // })
  },

  /**
   * 回调函数，把movs，写入data
   */
  Movies_SetPage: function(movs, idx, movie_lens) {
    //限定返回记录数
    if (movie_lens != 0) {
      movs.length = movie_lens
    }
    //添加 星数数组
    for (var index in movs) {
      movs[index].stars = util.voteToStarsArray(movs[index].vote_average)
    }
    //动态更新 数组的元素
    let bingo = 'moviesList[' + idx + '].movies'
    let bingo2 = 'moviesList[' + idx + '].listTitle'
    this.setData({
      [bingo]: movs,
      [bingo2]: app.globalData.tmdb_query_url[idx].title
    })
  },

  onCatchTapMoreMovie: function(event) {
    console.log(event.target.dataset.listid)
    wx.navigateTo({
      url: '/pages/movies/more-movies?listid=' + event.target.dataset.listid,
    })
  },

  SearchOnFocus: function(event) {
    console.log("--获得焦点")
  },

  SearchOnLoseFocus: function(event) {
    //真机时，这里会跳出小键盘，点击“完成”触发
    console.log("--bindconfirm确认输入")
    console.log(event.detail.value) //输入值
    if (event.detail.value.length > 0) {
      this.setData({
        insearch: true
      });
      let searchUrl = app.globalData.tmdb_multi_search_url + "?api_key=" + app.globalData.tmdb_api_key_v3 + "&query=" + encodeURI(event.detail.value) + "&page=" + "1";
      console.log(searchUrl)
      util.Movies_RequestMovieList(searchUrl, 0, 0, this.SearchMovies_SetPage)
    }
  },

  /**
   * 回调函数，把movs，写入data
   */
  SearchMovies_SetPage: function(movs, idx, movie_lens) {
    //添加 星数数组
    for (var index in movs) {
      movs[index].stars = util.voteToStarsArray(movs[index].vote_average)
    }
    //动态更新 数组的元素
    this.setData({
      searchResults: movs
    })
  },

  /**
   * 点击查询
   */
  StartSearch: function(event) {
    this.setData({
      insearch: true
    })
  },

  ExitSearch: function(event) {
    this.setData({
      insearch: false
    })
  },

  movieOnTap: function(event) {
    console.log(event.currentTarget.dataset.movieid);
    wx.navigateTo({
      url: 'movie-detail?movieid=' + event.currentTarget.dataset.movieid,
    });
  }
})